package com.pet.shop.service.room;

import com.alibaba.fastjson.JSONObject;
import com.pet.shop.entity.room.MonitorApp;
import com.pet.shop.mappers.room.MonitorAppMapper;
import com.pet.shop.utils.YsApiResult;
import com.pet.shop.utils.YsDeviceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
@EnableScheduling
public class MonitorAppUtil implements ApplicationListener<ContextRefreshedEvent> {

    private static MonitorApp monitorApp;

    @Autowired
    private MonitorAppMapper monitorAppMapper;

    protected static final Logger logger = LoggerFactory.getLogger(MonitorAppUtil.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        monitorApp = monitorAppMapper.getFirst();
        timerToNow();
    }

    public static MonitorApp getMonitorApp(){
        return monitorApp;
    }

    @Scheduled(cron = "0 0 0/3 * * ?")
    public void timerToNow(){
        Date now = new Date();
        logger.info("开始检查 token 是否过期：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));

        if(monitorApp.getExpireTime().getTime() - now.getTime() > 4 * 60 * 60 * 1000) {
            logger.info("未过期，不刷新");
            return;
        }

        JSONObject jsonObject = YsDeviceApi.refreshToken(monitorApp.getAppKey(), monitorApp.getAppSecret());
        if(!YsApiResult.SUCCESS.equals(jsonObject.getString("code"))){
            logger.error("刷新token失败：{}", jsonObject);
            return;
        }
        logger.info("刷新token：{}", jsonObject);
        monitorApp.setAccessToken(jsonObject.getJSONObject("data").getString("accessToken"));
        monitorApp.setExpireTime(jsonObject.getJSONObject("data").getDate("expireTime"));
        monitorAppMapper.update(monitorApp);
    }
}
